<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">订单详情</h2>
      </div>
      <div class="header-right">
        <!-- 待发货订单显示发货按钮 -->
        <el-button
            v-if="orderInfo && orderInfo.status === 6"
            type="danger"
            icon="Pointer"
            @click="handleSales"
        >
          处理
        </el-button>
        <!-- 待发货订单显示发货按钮 -->
        <el-button
            v-if="orderInfo && orderInfo.status === 2"
            type="success"
            icon="MessageBox"
            @click="handleShipping"
        >
          发货
        </el-button>
        <el-button type="primary" icon="Printer" @click="handlePrint">打印</el-button>
        <el-button icon="Back" @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-loading="loading" class="loading-container">
      <!-- 无数据提示 -->
      <div v-if="!loading && !orderInfo" class="no-data">
        <el-empty description="暂无订单数据">
          <el-button type="primary" @click="$router.go(-1)">返回</el-button>
        </el-empty>
      </div>

      <!-- 订单详情内容 -->
      <div v-if="orderInfo" class="order-detail-content">
        <!-- 订单信息卡片 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">订单信息</span>
            </div>
          </template>
          <div class="info-grid">
            <div class="info-row">
              <div class="info-item">
                <label>订单编号</label>
                <span>{{ orderInfo.platformOrderNo }}</span>
              </div>
              <div class="info-item">
                <label>发货单号</label>
                <span>{{ getDisplayValue(orderInfo.invoiceNumber, shouldShowInvoiceNumber) }}</span>
              </div>
              <div class="info-item">
                <label>订单状态</label>
                <span>{{ getOrderStatusText(orderInfo.status) }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <label>订单描述</label>
                <span>{{ orderInfo.platformOrderDesc || '-' }}</span>
              </div>
              <div class="info-item">
                <label>商品数量</label>
                <span>{{ orderInfo.count }}</span>
              </div>
              <div class="info-item">
                <label>商品总额</label>
                <span class="price">{{ orderInfo.platformOrderPrice }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <label>实付价格</label>
                <span class="price highlight">{{ orderInfo.realPrice }}</span>
              </div>
              <div class="info-item">
                <label>货源地</label>
                <span>{{ orderInfo.sourcesAddress || '-' }}</span>
              </div>
              <div class="info-item">
                <label>支付方式</label>
                <span>{{ getDisplayValue(getPayTypeText(orderInfo.payType), shouldShowPaymentInfo) }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <label>联系人姓名</label>
                <span>{{ orderInfo.contactName }}</span>
              </div>
              <div class="info-item">
                <label>联系人电话</label>
                <span>{{ orderInfo.contractTele }}</span>
              </div>
              <div class="info-item">
                <label>联系人地址</label>
                <span>{{ orderInfo.contractAddress }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <label>支付时间</label>
                <span>{{ getDisplayValue(parseTime(orderInfo.payTime), shouldShowPaymentInfo) }}</span>
              </div>
              <div class="info-item">
                <label>订单创建时间</label>
                <span>{{ parseTime(orderInfo.orderCreateTime) || '-' }}</span>
              </div>
              <div class="info-item">
                <label>订单完成时间</label>
                <span>{{ parseTime(orderInfo.orderCompleteTime) || '-' }}</span>
              </div>
            </div>
            <div class="info-row" v-if="orderInfo.remark">
              <div class="info-item full-width">
                <label>用户备注</label>
                <span>{{ orderInfo.remark }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <label>优惠券</label>
                <span>{{ orderInfo.couponsId || '-' }}</span>
              </div>
              <div class="info-item">
                <label>是否打印</label>
                <span>{{ orderInfo.isPrinted ? '是' : '否' }}</span>
              </div>
              <div class="info-item">
                <label>是否售后</label>
                <span>{{ orderInfo.isAfterSales ? '是' : '否' }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 商品信息卡片 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">商品信息</span>
            </div>
          </template>
          <div class="goods-table">
            <el-table :data="goodsList" border>
              <el-table-column label="商品主图" prop="image" align="center" width="100">
                <template #default="scope">
                  <div class="goods-image">
                    <el-image
                        :src="scope.row.image || '/default-product.png'"
                        fit="cover"
                        :preview-src-list="scope.row.image ? [scope.row.image] : []"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="goodName" align="center" min-width="150">
                <template #default="scope">
                  <span>{{ scope.row.goodName || orderInfo.platformOrderDesc || '商品名称' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品规格" prop="goodSize" align="center" width="120">
                <template #default="scope">
                  <span>{{ scope.row.goodSize || '默认规格' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品单价" prop="price" align="center" width="100">
                <template #default="scope">
                  <span class="price">{{
                      scope.row.price || orderInfo.goodPrice || orderInfo.platformOrderPrice || 0
                    }}</span>
                </template>
              </el-table-column>
              <el-table-column label="购买数量" prop="count" align="center" width="100">
                <template #default="scope">
                  <span>{{ scope.row.count || orderInfo.count || 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="小计" prop="realPrice" align="center" width="100">
                <template #default="scope">
                  <span class="price">{{
                      scope.row.realPrice || orderInfo.realPrice || ((scope.row.price || orderInfo.goodPrice || 0) * (scope.row.count || orderInfo.count || 1))
                    }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 发货弹窗 -->
    <el-dialog
        title="订单发货"
        v-model="shippingDialogVisible"
        width="500px"
        :before-close="handleCloseShippingDialog"
    >
      <el-form ref="shippingFormRef" :model="shippingForm" :rules="shippingRules" label-width="100px">
        <el-form-item label="发货单号" prop="invoiceNumber">
          <el-input
              v-model="shippingForm.invoiceNumber"
              placeholder="请输入发货单号"
              maxlength="20"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-select v-model="shippingForm.logisticsCompany" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰速运" value="SF"/>
            <el-option label="申通快递" value="STO"/>
            <el-option label="圆通速递" value="YTO"/>
            <el-option label="中通快递" value="ZTO"/>
            <el-option label="韵达速递" value="YD"/>
            <el-option label="京东物流" value="JD"/>
            <el-option label="其他" value="OTHER"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="shippingRemark">
          <el-input
              v-model="shippingForm.shippingRemark"
              type="textarea"
              :rows="3"
              placeholder="请输入发货备注（可选）"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseShippingDialog">取消</el-button>
          <el-button type="primary" @click="handleConfirmShipping" :loading="shippingLoading">
            确认发货
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import {useRoute, useRouter} from 'vue-router';
import {parseTime} from '@/utils/ruoyi';
import {updatePlatform} from '@/api/order/platform';
import {ElMessage, ElMessageBox} from 'element-plus';

const loading = ref(true);
const route = useRoute();
const router = useRouter();
const orderInfo = ref(null);
const goodsList = ref([]);

// 发货弹窗相关
const shippingDialogVisible = ref(false);
const shippingLoading = ref(false);
const shippingFormRef = ref(null);
const shippingForm = ref({
  invoiceNumber: '',
  logisticsCompany: '',
  shippingRemark: ''
});

const shippingRules = {
  invoiceNumber: [
    {required: true, message: '请输入发货单号', trigger: 'blur'},
    {min: 5, max: 50, message: '发货单号长度在 5 到 50 个字符', trigger: 'blur'}
  ],
  logisticsCompany: [
    {required: true, message: '请选择物流公司', trigger: 'change'}
  ]
};

// 计算属性
const shouldShowInvoiceNumber = computed(() => {
  if (!orderInfo.value) return false;
  // 待支付(1)、未发货(2)、已取消(5)的订单不显示发货单号
  return ![1, 2, 5].includes(orderInfo.value.status);
});

const shouldShowPaymentInfo = computed(() => {
  if (!orderInfo.value) return false;
  // 已取消(5)和待支付(1)的订单不显示支付信息
  return ![1, 5].includes(orderInfo.value.status);
});

onMounted(() => {
  try {
    if (route.query.orderData) {
      const orderData = JSON.parse(route.query.orderData);
      console.log('接收到的订单数据:', orderData);

      // 如果是数组，取第一个元素
      if (Array.isArray(orderData)) {
        orderInfo.value = orderData[0];
      } else {
        orderInfo.value = orderData;
      }

      // 处理商品列表数据
      if (orderInfo.value?.goodDetils && Array.isArray(orderInfo.value.goodDetils)) {
        goodsList.value = orderInfo.value.goodDetils;
      } else {
        // 如果没有商品详情，创建一个基于订单信息的商品项
        goodsList.value = [{
          goodName: orderInfo.value?.platformOrderDesc || '商品',
          goodSize: '默认规格',
          price: orderInfo.value?.goodPrice || orderInfo.value?.platformOrderPrice,
          count: orderInfo.value?.count || 1,
          realPrice: orderInfo.value?.realPrice || orderInfo.value?.platformOrderPrice,
          image: null
        }];
      }


    } else {
      console.warn('未找到订单数据');
      orderInfo.value = null;
      goodsList.value = [];
    }
  } catch (error) {
    console.error('解析订单数据失败:', error);
    orderInfo.value = null;
    goodsList.value = [];
  } finally {
    loading.value = false;
  }
});

// 订单状态转换函数
function getOrderStatusText(status) {
  const statusMap = {
    1: '待支付',
    2: '待发货',
    3: '已发货',
    4: '已完成',
    5: '已取消',
    6: '售后处理'
  };
  return statusMap[status] || '未知状态';
}


// 支付方式转换
function getPayTypeText(payType) {
  const payTypeMap = {
    1: '微信支付',
    2: '支付宝',
    3: '银行卡',
    4: '现金'
  };
  return payTypeMap[payType] || '微信支付';
}

// 统一处理字段显示值
function getDisplayValue(value, shouldShow) {
  if (!shouldShow) {
    return '-';
  }
  return value || '-';
}


// 发货相关函数
function handleShipping() {
  shippingDialogVisible.value = true;
}

function handleSales() {
  router.push({
    path: '/MallManagement/orderSet/afterSales',
    query: {}
  })
}

function handleCloseShippingDialog() {
  shippingDialogVisible.value = false;
  resetShippingForm();
}

function resetShippingForm() {
  shippingForm.value = {
    invoiceNumber: '',
    logisticsCompany: '',
    shippingRemark: ''
  };
  if (shippingFormRef.value) {
    shippingFormRef.value.resetFields();
  }
}

async function handleConfirmShipping() {
  if (!shippingFormRef.value) return;

  try {
    const valid = await shippingFormRef.value.validate();
    if (!valid) return;

    shippingLoading.value = true;

    // 更新订单状态为已发货
    await updatePlatform({
      ...orderInfo.value,
      status: 3, // 已发货
      invoiceNumber: shippingForm.value.invoiceNumber
    });

    // 更新本地数据
    orderInfo.value.status = 3;
    orderInfo.value.invoiceNumber = shippingForm.value.invoiceNumber;

    ElMessage.success('发货成功！');
    shippingDialogVisible.value = false;
    resetShippingForm();

  } catch (error) {
    console.error('发货失败:', error);
    ElMessage.error('发货失败，请重试');
  } finally {
    shippingLoading.value = false;
  }
}

// 打印功能
function handlePrint() {
  window.print();
}

</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

// 页面头部
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;

  .header-left {
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

// 加载容器
.loading-container {
  min-height: 400px;
}

// 订单详情内容
.order-detail-content {
  .detail-card {
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;

    :deep(.el-card__header) {
      background-color: #f8f9fa;
      border-bottom: 1px solid #e4e7ed;
      padding: 15px 20px;

      .card-header {
        .card-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }

    :deep(.el-card__body) {
      padding: 20px;
    }
  }
}

// 信息网格布局
.info-grid {
  border: 1px solid #e4e7ed;
  border-radius: 4px;

  .info-row {
    display: flex;
    border-bottom: 1px solid #e4e7ed;

    &:last-child {
      border-bottom: none;
    }

    .info-item {
      flex: 1;
      display: flex;
      align-items: center;
      min-height: 48px;
      padding: 12px 16px;
      border-right: 1px solid #e4e7ed;

      &:last-child {
        border-right: none;
      }

      &.full-width {
        flex: 3;
        border-right: none;
      }

      label {
        display: inline-block;
        min-width: 120px;
        font-weight: 500;
        color: #303133;
        margin-right: 0;
        text-align: center;
        flex-shrink: 0;
        background-color: #f5f7fa;
        padding: 12px 8px;
        border-right: 1px solid #e4e7ed;
        margin: -12px 12px -12px -16px;
      }

      span {
        color: #303133;
        flex: 1;
        word-break: break-all;

        &.price {
          font-weight: 600;
          color: #f56c6c;

          &.highlight {
            font-size: 18px;
            color: #e6a23c;
          }
        }
      }


      .status-content {
        display: flex;
        flex-direction: column;
        gap: 8px;
        flex: 1;
      }
    }
  }
}

// 商品表格
.goods-table {
  :deep(.el-table) {
    .goods-image {
      width: 60px;
      height: 60px;
      border-radius: 6px;
      overflow: hidden;
      border: 1px solid #e4e7ed;
      margin: 0 auto;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }

    .price {
      font-weight: 600;
      color: #f56c6c;
    }

    // 表格行高度调整
    .el-table__row {
      height: 80px;
    }

    .el-table__cell {
      padding: 8px 0;
      vertical-align: middle;
    }
  }
}

// 无数据状态
.no-data {
  text-align: center;
  padding: 60px 20px;
}

// 打印样式
@media print {
  .page-header .header-right {
    display: none;
  }

  .detail-card {
    border: 1px solid #000 !important;
    box-shadow: none !important;
    margin-bottom: 20px !important;
    page-break-inside: avoid;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;

    .header-right {
      align-self: flex-end;
    }
  }

  .info-row {
    flex-direction: column;
    gap: 15px;

    .info-item {
      flex-direction: column;
      align-items: flex-start;

      label {
        min-width: auto;
        margin-bottom: 5px;
      }
    }
  }

  .goods-info {
    .goods-image {
      width: 50px;
      height: 50px;
    }
  }
}
</style>